package com.ljl.service;

import com.alibaba.fastjson.JSONObject;
import com.ljl.config.BaiduProperties;
import com.ljl.entity.BodyAnalysisResponse;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * @author 刘家良
 * @date 2022/10/30 16:46
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BaiduService {

    private final BaiduProperties baiduProperties;
    private final RestTemplate restTemplate;

    /**
     * 获取百度api调用凭证
     * @return /
     */
    private String getAccessToken() {
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        url = url + "?grant_type=client_credentials&client_id=" + baiduProperties.getApiKey() + "&client_secret=" + baiduProperties.getSecretKey();
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        return forObject.getString("access_token");
    }

    /**
     * 人体关键点分析
     * @param imgBase64 图片的base64
     * @return 调用结果/
     */
    public BodyAnalysisResponse bodyAnalysis(String imgBase64) {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_analysis";
        url = url + "?access_token=" + getAccessToken();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("image", imgBase64);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return JSONObject.parseObject(exchange.getBody(), BodyAnalysisResponse.class);
    }

}
